package ximage

import (
	"image"
	"image/draw"
	"os"
	"path/filepath"
)

//CutIamge裁剪图片相关的信息封装
type CutImage struct {
	//原始图片文件名
	SrcImageFileName string
	//生成裁剪后的图片文件名
	DestImageFileName string
	//生成裁剪后的图片宽
	DestImageWidth int
	//生成裁剪后的图片高
	DestImageHeight int
	//原图片裁剪起始的位置
	SrcImageStartPoint image.Point
}

//CutSrcImage裁剪图片
func (this *CutImage) CutSrcImage() error {

	srcFile, err := os.Open(this.SrcImageFileName)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	srcImg, _, err := image.Decode(srcFile)
	if err != nil {
		return err
	}

	destImageFile, err := os.Create(this.DestImageFileName)
	if err != nil {
		return err
	}
	defer destImageFile.Close()

	var cutRect = image.Rect(0, 0, this.DestImageWidth, this.DestImageHeight)
	var lastIamge = image.NewNRGBA(cutRect)
	draw.Draw(lastIamge, cutRect, srcImg, this.SrcImageStartPoint, draw.Src)

	ext := filepath.Ext(this.DestImageFileName)
	if dofunc, ok := writeImageFunMap[ext]; ok {
		return dofunc(destImageFile, lastIamge)
	} else {
		return fileExtNotSupport
	}
}
